<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "buyer_qr".
 *
 * @property int $id
 * @property int $type
 * @property int $type_id
 * @property int $cashback_fee 返现金额
 * @property string|null $content
 * @property int|null $qr_id
 * @property int $ctime
 */
class BuyerQr extends \yii\db\ActiveRecord
{
    const TYPE_USER = 1;
    //获取用户账户，如果没有就创建一个
    static public function getAndCreateObj($type_id,$type=self::TYPE_USER){
        $obj = self::findOne(['type'=>$type,'type_id'=>$type_id]);
        if(empty($obj)){
            $obj = new self();
            $obj->type = $type;
            $obj->type_id = $type_id;
            $obj->content = '空';
            $obj->ctime = time();
            if(!$obj->save()){
                throw new \Exception(json_encode($obj->getErrors(),JSON_UNESCAPED_UNICODE),1);
            }
        }
        return $obj;
    }
    //获取二维码str
    public function getQrObj(){
        if(!empty($this->qr_id)){
            return $this->qr;
        }
        $wxAccount = WxAccountMini::findOne(2);
        $arr = $wxAccount->getMiniQrB([
            'scene'=>'1:'.$this->id
        ]);
        $uploadFile = UploadFile::addToOssByBuffer($arr,UploadFile::PATH_QR);
        $this->qr_id = $uploadFile->id;
        $this->save();
        return $this->qr;
    }
    //关联发布
    public function getQr(){
        return $this->hasOne(UploadFile::className(),['id'=>'qr_id']);
    }
    //关联发布
    public function getUser(){
        return $this->hasOne(WxUser::className(),['id'=>'wx_uid']);
    }
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'buyer_qr';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['type', 'type_id', 'ctime'], 'required'],
            [['type', 'type_id', 'cashback_fee', 'qr_id', 'ctime'], 'integer'],
            [['content'], 'string'],
            [['type', 'type_id'], 'unique', 'targetAttribute' => ['type', 'type_id']],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'type' => 'Type',
            'type_id' => 'Type ID',
            'cashback_fee' => '返现金额(分)',
            'content' => '说明',
            'qr_id' => 'Qr ID',
            'ctime' => 'Ctime',
        ];
    }
}
